package com.rritw.webtools.action.tool;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;

import com.alibaba.druid.sql.SQLUtils;
import com.rritw.webtools.action.IpsAction;
import com.rritw.webtools.util.StringUtil;

@Controller
@Scope("prototype")
public class FormatSQLAction extends IpsAction {

    private static final long   serialVersionUID = -6151910872231333075L;
    private static final Logger log              = Logger.getLogger(FormatSQLAction.class);
    private String              content;
    private String              requestType;

    private String              contentResult;

    public String index() {
        super.init();
        return SUCCESS;
    }

    public String create() {
        try {
            super.init();
            if ("mysql".equals(requestType)) {
                contentResult = SQLUtils.formatMySql(content);
            } else if ("oracle".equals(requestType)) {
                contentResult = SQLUtils.formatOracle(content);
            } else if ("postgre".equals(requestType)) {
                contentResult = SQLUtils.formatPGSql(content);
            } else if ("sqlserver".equals(requestType)) {
                contentResult = SQLUtils.formatSQLServer(content);
            } else if ("odps".equals(requestType)) {
                contentResult = SQLUtils.formatOdps(content);
            } else {
                contentResult = "SQL type is not correct.";
                return ERROR;
            }
            if (!StringUtil.isEmpty(content)) {
                content = HtmlUtils.htmlEscape(content);
            }
            if (!StringUtil.isEmpty(contentResult)) {
                contentResult = HtmlUtils.htmlEscape(contentResult);
            }
        } catch (Exception e) {
            log.error("Format xml exception happened:" + e.getMessage(), e);
        }
        return SUCCESS;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getContentResult() {
        return contentResult;
    }

    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    public String getRequestType() {
        return requestType;
    }

}
